import React, { useEffect, useState, useCallback, useRef } from 'react'
import Taro, { useShareAppMessage, useShareTimeline, useDidShow } from '@tarojs/taro'
import { View, Button, Image, Text, ScrollView, Swiper, SwiperItem } from '@tarojs/components'
import { useSelector, useDispatch } from 'react-redux'
import { SpImage } from '@/components'
import { AtModal, AtModalHeader, AtModalContent, AtModalAction } from 'taro-ui'
import {
  SpScreenAd,
  SpPage,
  SpSearch,
  SpRecommend,
  SpPrivacyModal,
  SpTabbar,
  SpCouponPackage
} from '@/components'

import S from '@/spx'
import api from '@/api'
import {
  isWeixin,
  isEmpty,
  getDistributorId,
  VERSION_STANDARD,
  VERSION_PLATFORM,
  classNames,
  getCurrentPageRouteParams,
  resolveStringifyParams,
  isAPP,
  isSystem
} from '@/utils'
import qs from 'qs'
import { WgtHomeHeader } from '@/pages/home/wgts'
import entryLaunch from '@/utils/entryLaunch'
import { updateLocation, fetchUserFavs } from '@/store/slices/user'
import { updateShopInfo } from '@/store/slices/shop'
import { useImmer } from 'use-immer'
import { useLogin, useNavigation } from '@/hooks'
import GoodsList from './home/wgts/goods-list'
import HomeWgts from './home/comps/home-wgts'
import CompAddTip from './home/comps/comp-addtip'
import CompFloatMenu from './home/comps/comp-floatmenu'

import './home/index.scss'

const MCompAddTip = React.memo(CompAddTip)
const MSpPrivacyModal = React.memo(SpPrivacyModal)

const initialState = {
  wgts: [],
  showBackToTop: false,
  loading: true,
  groupsList: [],
  gseasonList1: [],
  gseasonList2: [],
  gseasonList3: [],
  gseasonList4: [],
  communityList: []
}

function Home() {
  const [state, setState] = useImmer(initialState)
  const [likeList, setLikeList] = useImmer([])

  const { initState, openRecommend, openLocation, openStore, appName } = useSelector(
    (state) => state.sys
  )
  const fetchLocationTiem = Taro.getStorageSync('fetchLocationTiem')
  const newFetchLocationTiem = Date.now()

  const { isLogin, login, checkPolicyChange } = useLogin({
    policyUpdateHook: (isUpdate) => {
      if (isUpdate) {
        setPolicyModal(true)
      }
    }
  })

  const [policyModal, setPolicyModal] = useState(false)
  const showAdv = useSelector((member) => member.user.showAdv)
  const { location } = useSelector((state) => state.user)
  const { openScanQrcode } = useSelector((state) => state.sys)
  const { setNavigationBarTitle } = useNavigation()

  const {
    wgts,
    loading,
    groupsList,
    gseasonList1,
    gseasonList2,
    gseasonList3,
    gseasonList4,
    communityList
  } = state

  const dispatch = useDispatch()

  useEffect(() => {
    if (initState) {
      init()
    }
  }, [initState])

  useDidShow(() => {
    if (isAPP()) {
      getAppversionCode()
    }
    setNavigationBarTitle(appName)
    // 检查隐私协议是否变更或同意
    checkPolicyChange()
  })

  const init = async () => {
    // if (!VERSION_STANDARD) {
    getGroupsList()
    getGseasonList()
    // getHomeCommunityList()
    await fetchWgts()
    // }
  }
  const getAppversionCode = async () => {
    if (isSystem() == 'Android') {
      const res = await Taro.request({
        url: 'https://admin.mimijishi.com/api/appUpdate',
        data: {
          name: 'app.client'
        }
      })
      const result = res.data.data
      const verCode = plus.runtime.versionCode //客户端的版本号
      if (result.code > verCode) {
        Taro.showModal({
          title: '已经有新版本了哟~',
          content: result.content,
          confirmText: '去更新',
          success: (res) => {
            if (res.confirm) {
              downloadNewVersion(result.url)
            }
          }
        })
      }
    }
  }

  const downloadNewVersion = (url) => {
    Taro.showLoading({
      title: '下载中...',
      mask: true
    })
    var dtask = plus.downloader.createDownload(
      url,
      {
        filename: '_downloads/'
      },
      function (d, status) {
        // 下载完成
        if (status == 200) {
          plus.runtime.install(
            d.filename,
            {
              force: false
            },
            function () {},
            (e) => {}
          )
          Taro.hideLoading()
        } else {
          plus.nativeUI.alert('下载升级包失败，请手动去站点下载安装，错误码: ' + status)
        }
      }
    )
    dtask.start()
  }

  const fetchWgts = async () => {
    const { config } = await api.shop.getShopTemplate({
      distributor_id: getDistributorId()
    })
    setState((draft) => {
      draft.wgts = config
      draft.loading = false
    })
    // fetchLikeList()
  }

  const fetchLikeList = async () => {
    if (openRecommend == 1) {
      const query = {
        page: 1,
        pageSize: 30
      }
      const { list } = await api.cart.likeList(query)
      setLikeList(list)
    }
  }

  // 定位
  const fetchLocation = async () => {
    try {
      const res = await entryLaunch.getCurrentAddressInfo()
      dispatch(updateLocation(res))
    } catch (e) {
      // 定位失败，获取默认店铺
    }
    setState((draft) => {
      draft.isOpened = false
    })
    if (VERSION_STANDARD) {
      fetchStoreInfo(location)
    }
  }
  const handleConfirmModal = useCallback(async () => {
    setPolicyModal(false)
    // if (
    //   !location &&
    //   ((VERSION_STANDARD && openLocation == 1) || VERSION_PLATFORM) &&
    //   newFetchLocationTiem - fetchLocationTiem > 172800000
    // ) {
    //   setState((draft) => {
    //     draft.isOpened = true
    //   })
    // }
  }, [])

  useShareAppMessage(async (res) => {
    const { title, imageUrl } = await api.wx.shareSetting({ shareindex: 'index' })
    const params = getCurrentPageRouteParams()
    const { userId } = Taro.getStorageSync('userinfo')
    params.shareUserId = userId
    params.company_id = process.env.APP_COMPANY_ID
    const path = `/pages/index?${isEmpty(params) ? `` : `${resolveStringifyParams(params)}`}`
    return {
      title: title,
      imageUrl: imageUrl,
      path
    }
  })

  useShareTimeline(async (res) => {
    const { title, imageUrl } = await api.wx.shareSetting({ shareindex: 'index' })
    const params = getCurrentPageRouteParams()
    const { userId } = Taro.getStorageSync('userinfo')
    params.shareUserId = userId
    params.company_id = process.env.APP_COMPANY_ID
    return {
      title: title,
      imageUrl: imageUrl,
      query: resolveStringifyParams(params)
    }
  })

  const fetchStoreInfo = async (location) => {
    let params = {
      distributor_id: getDistributorId() // 如果店铺id和经纬度都传会根据哪个去定位传参
    }
    if (openLocation == 1 && location) {
      const { lat, lng } = location
      params.lat = lat
      params.lng = lng
      // params.distributor_id = undefined
    }
    const res = await api.shop.getShop(params)
    dispatch(updateShopInfo(res))
    await fetchWgts()
  }
  const paddingTop = Taro.getWindowInfo()?.statusBarHeight

  const headHeight = !isWeixin
    ? 45
    : Taro.getMenuButtonBoundingClientRect()?.height +
      (Taro.getMenuButtonBoundingClientRect()?.top - Taro.getWindowInfo()?.statusBarHeight) * 2

  const searchHeight = (paddingTop ? paddingTop : 0) + headHeight + 5

  const searchComp = wgts.find((wgt) => wgt.name == 'search')

  const pageData = wgts.find((wgt) => wgt.name == 'page')
  let filterWgts = []
  if (searchComp && searchComp.config.fixTop) {
    filterWgts = wgts.filter((wgt) => wgt.name !== 'search' && wgt.name != 'page')
  } else {
    filterWgts = wgts.filter((wgt) => wgt.name != 'page')
  }

  const fixedTop = searchComp && searchComp.config.fixTop

  const isShowHomeHeader =
    VERSION_PLATFORM ||
    (openScanQrcode == 1 && isWeixin) ||
    (VERSION_STANDARD && openStore && openLocation == 1) ||
    fixedTop

  const getGroupsList = async () => {
    const res = await api.item.groupsList({
      page: 1,
      pageSize: 20,
      group_goods_type: 'normal',
      view: 2,
      team_status: 0,
      distributor_id: 0,
      company_id: 1
    })
    setState((draft) => {
      draft.groupsList = res.list
    })
  }
  const getGseasonList = async () => {
    const res = await api.item.xitems({
      approve_status: 'onsale,only_show',
      item_type: 'normal',
      company_id: 1
    })
    let list1 = []
    let list2 = []
    let list3 = []
    let list4 = []
    res.map((item, i) => {
      if (i < 4) {
        list1.push(item)
      } else if (i < 8) {
        list2.push(item)
      } else if (i < 12) {
        list3.push(item)
      } else if (i < 16) {
        list4.push(item)
      }
    })
    setState((draft) => {
      draft.gseasonList1 = list1
      draft.gseasonList2 = list2
      draft.gseasonList3 = list3
      draft.gseasonList4 = list4
    })
  }
  const handleGoodsClick = (item) => {
    const { item_id, distributor_id } = item
    let query = { id: item_id }
    if (typeof distributor_id != 'undefined') {
      query.dtid = distributor_id
    }

    Taro.navigateTo({
      url: `/pages/item/espier-detail?${qs.stringify(query)}`
    })
  }

  const getHomeCommunityList = async () => {
    const res = await api.community.getHomeCommunityList()
    let list = res.filter((item) => item.category_name != '测试')
    setState((draft) => {
      draft.communityList = list
    })
  }
  const share = () => {}
  const servicePhone = () => {
    if (!isWeixin) {
      Taro.showModal({
        title: '联系客服',
        content: '客服电话为400-9969-469',
        confirmText: '拨打电话',
        success: function (res) {
          if (res.confirm) {
            Taro.makePhoneCall({
              phoneNumber: '4009969469' //仅为示例，并非真实的电话号码
            })
          }
        }
      })
    }
  }

  return (
    <SpPage
      className='page-index'
      scrollToTopBtn
      // renderNavigation={renderNavigation()}
      pageConfig={pageData?.base}
      renderFloat={wgts.length > 0 && <CompFloatMenu />}
      renderFooter={<SpTabbar />}
      loading={loading}
      isNav={false}
    >
      <View
        className={classNames('home-body', {
          'has-home-header': isShowHomeHeader && isWeixin
        })}
      >
        <View
          className='home-header'
          style={{ paddingTop: paddingTop + 'px', height: headHeight + 'px' }}
        >
          <Image
            className='home-logo'
            src={process.env.APP_IMAGE_CDN + '/logo01.png'}
            lazyLoad
          ></Image>
          <Image
            className='home-agentQy'
            src={process.env.APP_IMAGE_CDN + '/agent-qy.png'}
            lazyLoad
          ></Image>
          <WgtHomeHeader locationKey='address'></WgtHomeHeader>
        </View>

        <View className='home-search-box' style={{ marginTop: searchHeight + 'px' }}>
          {isShowHomeHeader && fixedTop && (
            <View
              className='home-search'
              onClick={() => {
                Taro.navigateTo({
                  url: `/pages/item/list`
                })
              }}
            >
              搜索想要的商品<View className='home-search-but'>搜索</View>
            </View>
          )}
          {/* {isWeixin && (
            <View className='home-search-but'>
              <Image
                className='home-search-icon'
                src={process.env.APP_IMAGE_CDN + '/share.png'}
              ></Image>
              <Text className='home-search-txt'>分享</Text>
            </View>
          )} */}
          <Button className='home-search-but' openType='contact' onClick={servicePhone}>
            <Image
              className='home-search-icon'
              src={process.env.APP_IMAGE_CDN + '/wechat.png'}
              lazyLoad
            ></Image>
            <Text className='home-search-txt'>客服</Text>
          </Button>
          {/* <View>
            
          </View> */}
        </View>

        <HomeWgts wgts={filterWgts} onLoad={fetchLikeList} pageName='shouye'>
          {/* 社区团购 */}
          <View className='group'>
            <View className='group-title'>
              <Text className='group-title-text'>今日团购</Text>
              {/* <Text className='group-title-tag'>限量好货 爆款低价天天抢</Text> */}
            </View>
            <View
              className='group-list'
              onClick={() => {
                Taro.navigateTo({
                  url: `/marketing/pages/item/group-list`
                })
              }}
            >
              {groupsList.map((item, idx) => (idx<3&&
                <View className='group-list-item' key={`groupscroll-item__${idx}`}>
                    <SpImage className='group-list-item-img' lazyLoad src={item.pics} mode='scaleToFill'   />
                    {/* <Image className='group-list-item-img' src={item.pics} lazyLoad></Image> */}
                    {/* <View className='group-list-item-price'>
                      <Text className='rmbSymbol'>￥</Text>
                      {item.act_price / 100}
                    </View> */}
                    <View className='group-list-item-marketPrice'>
                      <Text className='rmbSymbol'>￥</Text>
                      {item.price / 100}
                  </View>
                </View>
              ))}
            </View>
          </View>
          {/* 猜你喜欢 */}
          <SpRecommend className='recommend-block' info={likeList} />

          {/* 社区服务 */}
          {/* <View className='community'>
            <View className='community-title'>
              <Text className='community-title-text'>社区服务</Text>
              <Text className='community-title-tag'>优价优服务</Text>
            </View>
            <View className='community-list'>
              {communityList.map((item, idx) => (
                <View
                  className='community-list-item'
                  key={`communityscroll-item__${idx}`}
                  onClick={() => {
                    Taro.navigateTo({
                      url: `/pages/custom/custom-page?id=${item.pageInfo.id}`
                    })
                  }}
                >
                  <Image
                    className='community-list-item-img'
                    src={item.pageInfo?.page_share_imageUrl}
                    lazyLoad
                  ></Image>
                </View>
              ))}
            </View>
          </View>
          
          {/* 时令新品 */}
          {/* <View className='season'>
            <View className='season-title'>
              <Text className='season-title-text'>时令新品</Text>
              <Text className='season-title-tag'>时令上新</Text>
            </View>
            <View className='season-list'>
              <Swiper circular autoplay className='test-ph'>
                <SwiperItem className='test-h'>
                  {gseasonList1.map((item, idx) => (
                    <View
                      className='season-list-item'
                      key={`gseasonList1-item__${idx}`}
                      onClick={() => {
                        handleGoodsClick(item)
                      }}
                    >
                      <Image className='season-list-item-img' src={item.pics} lazyLoad></Image>
                      <View className='season-list-item-price'>
                        <Text className='rmbSymbol'>￥</Text>
                        {item.price / 100}
                      </View>
                    </View>
                  ))}
                </SwiperItem>
                <SwiperItem className='test-h'>
                  {gseasonList2.map((item, idx) => (
                    <View
                      className='season-list-item'
                      key={`gseasonList2-item__${idx}`}
                      onClick={() => {
                        handleGoodsClick(item)
                      }}
                    >
                      <Image className='season-list-item-img' src={item.pics} lazyLoad></Image>
                      <View className='season-list-item-price'>
                        <Text className='rmbSymbol'>￥</Text>
                        {item.price / 100}
                      </View>
                    </View>
                  ))}
                </SwiperItem>
                <SwiperItem className='test-h'>
                  {gseasonList3.map((item, idx) => (
                    <View
                      className='season-list-item'
                      key={`gseasonList3-item__${idx}`}
                      onClick={() => {
                        handleGoodsClick(item)
                      }}
                    >
                      <Image className='season-list-item-img' src={item.pics} lazyLoad></Image>
                      <View className='season-list-item-price'>
                        <Text className='rmbSymbol'>￥</Text>
                        {item.price / 100}
                      </View>
                    </View>
                  ))}
                </SwiperItem>
                <SwiperItem className='test-h'>
                  {gseasonList4.map((item, idx) => (
                    <View
                      className='season-list-item'
                      key={`gseasonList4-item__${idx}`}
                      onClick={() => {
                        handleGoodsClick(item)
                      }}
                    >
                      <Image className='season-list-item-img' src={item.pics} lazyLoad></Image>
                      <View className='season-list-item-price'>
                        <Text className='rmbSymbol'>￥</Text>
                        {item.price / 100}
                      </View>
                    </View>
                  ))}
                </SwiperItem>
              </Swiper>
            </View>
          </View> */}
          
          {<View style={{marginTop:"10px"}}></View>}

        </HomeWgts>
        
      </View>

      {/* 小程序搜藏提示 */}
      {isWeixin && <MCompAddTip />}

      {/* 开屏广告 */}
      {isWeixin && !showAdv && <SpScreenAd />}

      {/* 隐私政策 */}
      <MSpPrivacyModal
        open={policyModal}
        onCancel={() => {
          setPolicyModal(false)
        }}
        onConfirm={handleConfirmModal}
      />

      {/* 优惠券包 */}
      {VERSION_STANDARD && <SpCouponPackage />}
    </SpPage>
  )
}

export default Home
